package com.xingongchang.baolebei.fragment;

import java.io.File;
import java.net.URL;

import org.afinal.simplecache.ACache;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.ContactsContract.CommonDataKinds.Phone;
import android.provider.MediaStore;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.ImageView.ScaleType;

import com.external.activeandroid.query.Select;
import com.external.androidquery.callback.AjaxStatus;
import com.external.maxwin.view.XListView;
import com.external.maxwin.view.XListView.IXListViewListener;
import com.google.gson.JsonObject;
import com.insthub.BeeFramework.fragment.BaseFragment;
import com.insthub.BeeFramework.model.BusinessResponse;
import com.insthub.BeeFramework.view.RoundImageView;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.ImageLoaderConfiguration;
import com.umeng.analytics.MobclickAgent;
import com.umeng.fb.FeedbackAgent;
import com.xingongchang.baolebei.BaolebeiApp;
import com.xingongchang.baolebei.ImageDisplay;
import com.xingongchang.baolebei.R;
import com.xingongchang.baolebei.activity.AddressListActivity;
import com.xingongchang.baolebei.activity.CollectionActivity;
import com.xingongchang.baolebei.activity.HistoryActivity;
import com.xingongchang.baolebei.activity.InfoActivity;
import com.xingongchang.baolebei.activity.ProfileActivity;
import com.xingongchang.baolebei.activity.SettingActivity;
import com.xingongchang.baolebei.activity.SigninActivity;
import com.xingongchang.baolebei.model.LoginModel;
import com.xingongchang.baolebei.model.ProtocolConst;
import com.xingongchang.baolebei.model.UserInfoModel;
import com.xingongchang.baolebei.protocol.SESSION;
import com.xingongchang.baolebei.protocol.USER;
import com.xingongchang.baolebei.protocol.USER_INFO;

/**
 * 身份主页
 */
public class ProfileFragment extends BaseFragment implements
		IXListViewListener, OnClickListener, BusinessResponse {
	private View view;
	private View headView;
	private XListView xlistView;

	private ImageView setting;
	private RoundImageView photo;
	private ImageView camera;

	private TextView name;
	private FrameLayout payment;
	private TextView payment_num;
	private FrameLayout ship;
	private TextView ship_num;
	private FrameLayout receipt;
	private TextView receipt_num;
	private FrameLayout history;
	private TextView history_num;
	private TextView collect_num;

	private LinearLayout collect;
	private LinearLayout address_manage;
	private LinearLayout profile_head_collect4;
	private LinearLayout yijian;

	private LinearLayout help;
	FeedbackAgent agent;

	private USER user;
	private UserInfoModel userInfoModel;

	private SharedPreferences shared, share;
	private SharedPreferences.Editor editor;

	private ImageView image;
	private int uid;
	private boolean isRefresh = false;
	protected Context mContext;
	ImageLoader imageLoader = ImageLoader.getInstance();
	public USER_INFO info;
	private Button profile_user;
	String id;
	int iid;
	ACache aCache;
	NetworkInfo mNetworkInfo;// 判断网络是否连接

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		agent = new FeedbackAgent(getActivity());
		agent.sync();

	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		view = inflater.inflate(R.layout.profile, null);
		mContext = getActivity();
		// 缓存
		aCache = ACache.get(getActivity());
		// 判断是否连接网络
		ConnectivityManager mConnectivityManager = (ConnectivityManager) getActivity()
				.getSystemService(Context.CONNECTIVITY_SERVICE);
		mNetworkInfo = mConnectivityManager.getActiveNetworkInfo();
		imageLoader.init(ImageLoaderConfiguration.createDefault(mContext));
		share = getActivity().getSharedPreferences("sns", Context.MODE_PRIVATE);
		shared = getActivity().getSharedPreferences("userInfo", 0);
		headView = LayoutInflater.from(getActivity()).inflate(
				R.layout.profile_head, null);

		image = (ImageView) view.findViewById(R.id.profile_setting);
		image.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {

				Intent intent = new Intent(getActivity(), SettingActivity.class);
				startActivity(intent);
				getActivity().overridePendingTransition(R.anim.push_right_in,
						R.anim.push_right_out);
			}
		});

		xlistView = (XListView) view.findViewById(R.id.profile_list);
		xlistView.addHeaderView(headView);
		xlistView.setPullLoadEnable(false);
		xlistView.setRefreshTime();
		xlistView.setXListViewListener(this, 1);
		xlistView.setAdapter(null);

		setting = (ImageView) headView.findViewById(R.id.profile_head_setting);
		photo = (RoundImageView) headView.findViewById(R.id.profile_head_photo);
		camera = (ImageView) headView.findViewById(R.id.profile_head_camera);
		name = (TextView) headView.findViewById(R.id.profile_head_name);

		payment = (FrameLayout) headView
				.findViewById(R.id.profile_head_payment);
		payment_num = (TextView) headView
				.findViewById(R.id.profile_head_payment_num);

		ship = (FrameLayout) headView.findViewById(R.id.profile_head_ship);
		ship_num = (TextView) headView.findViewById(R.id.profile_head_ship_num);

		receipt = (FrameLayout) headView
				.findViewById(R.id.profile_head_receipt);
		receipt_num = (TextView) headView
				.findViewById(R.id.profile_head_receipt_num);

		history = (FrameLayout) headView
				.findViewById(R.id.profile_head_history);
		history_num = (TextView) headView
				.findViewById(R.id.profile_head_history_num);

		collect = (LinearLayout) headView
				.findViewById(R.id.profile_head_collect);
		address_manage = (LinearLayout) headView
				.findViewById(R.id.profile_head_address_manage);
		collect_num = (TextView) headView
				.findViewById(R.id.profile_head_collect_num);
		help = (LinearLayout) headView.findViewById(R.id.profile_help);
		profile_head_collect4 = (LinearLayout) headView
				.findViewById(R.id.profile_head_collect4);
		yijian = (LinearLayout) headView.findViewById(R.id.yijian);
		profile_user = (Button) view.findViewById(R.id.profile_user);
		yijian.setOnClickListener(this);
		profile_head_collect4.setOnClickListener(this);
		profile_user.setOnClickListener(this);

		setting.setOnClickListener(this);
		camera.setOnClickListener(this);
		payment.setOnClickListener(this);
		ship.setOnClickListener(this);
		receipt.setOnClickListener(this);
		history.setOnClickListener(this);
		collect.setOnClickListener(this);
		address_manage.setOnClickListener(this);
		name.setOnClickListener(this);
		help.setOnClickListener(this);
		photo.setOnClickListener(this);
		userInfoModel = new UserInfoModel(getActivity());
		userInfoModel.addResponseListener(this);
		SESSION session = SESSION.getInstance();
		if ("".equals(session.uid)) {
			Resources resource = mContext.getResources();
			String click = resource.getString(R.string.click_to_login);
			name.setText(click);
			camera.setVisibility(View.GONE);
			photo.setImageResource(R.drawable.profile_no_avarta_icon);
			profile_user.setVisibility(View.GONE);
		}else{
			userInfoModel.getUserInfo();
		}
		return view;
	}
	public void  cache(){
		if(mNetworkInfo==null){
			JSONObject jsonObject=aCache.getAsJSONObject("objects");
			 try
			{
				SESSION session = SESSION.getInstance();
				USER suser = USER.fromJson(jsonObject);
				if(!"".equals(session.uid)){
					ImageDisplay.show(mContext, suser.user_photo, photo);
					name.setText(suser.nickname);
				}
			} catch (JSONException e)
			{
				e.printStackTrace();
			}
		}
	}

	@Override
	public void onResume() {
		super.onResume();
		SESSION session = SESSION.getInstance();
		if (!"".equals(session.uid)) {
			if (isRefresh == true) {
				userInfoModel.getUserInfo();
			}
		}
		MobclickAgent.onPageStart("Profile");
	}

	public void setUserInfo() {
		ImageDisplay.show(mContext, user.user_photo, photo);
		name.setText(user.nickname);
		Resources resource = mContext.getResources();
		if (!user.order_num.await_pay.equals("0")) {
			payment_num.setVisibility(View.VISIBLE);
			payment_num.setText(user.order_num.await_pay);
		} else {
			payment_num.setVisibility(View.GONE);
		}

		if (!user.order_num.await_ship.equals("0")) {
			ship_num.setVisibility(View.VISIBLE);
			ship_num.setText(user.order_num.await_ship);
		} else {
			ship_num.setVisibility(View.GONE);
		}

		if (!user.order_num.shipped.equals("0")) {
			receipt_num.setVisibility(View.VISIBLE);
			receipt_num.setText(user.order_num.shipped);
		} else {
			receipt_num.setVisibility(View.GONE);
		}

//		if (!user.order_num.finished.equals("0")) {
//			history_num.setVisibility(View.VISIBLE);
//			history_num.setText(user.order_num.finished);
//		} else {
//			history_num.setVisibility(View.GONE);
//		}
		if (user.collection_num.equals("0")) {
			collect_num.setText(resource.getString(R.string.no_product));
		} else {
			collect_num.setText(user.collection_num
					+ resource.getString(R.string.no_of_items));
		}
	}

	@Override
	public void onClick(View v) {

		Intent intent;
		switch (v.getId()) {
		case R.id.profile_head_setting:
			if (uid == 0) {
				isRefresh = true;
				intent = new Intent(getActivity(), SigninActivity.class);
				startActivity(intent);
				getActivity().overridePendingTransition(R.anim.push_buttom_in,
						R.anim.push_buttom_out);
			} else {
				isRefresh = false;
				intent = new Intent(getActivity(), SettingActivity.class);
				startActivity(intent);
				getActivity().overridePendingTransition(R.anim.push_right_in,
						R.anim.push_right_out);
			}
			break;
		case R.id.profile_head_payment:
			if (uid == 0) {
				isRefresh = true;
				intent = new Intent(getActivity(), SigninActivity.class);
				startActivity(intent);
				getActivity().overridePendingTransition(R.anim.push_buttom_in,
						R.anim.push_buttom_out);
			} else {
				isRefresh = true;
				intent = new Intent(getActivity(), HistoryActivity.class);
				intent.putExtra("flag", "await_pay");
				startActivityForResult(intent, 2);
				getActivity().overridePendingTransition(R.anim.push_right_in,
						R.anim.push_right_out);
			}
			break;
		case R.id.profile_head_ship:
			if (uid == 0) {
				isRefresh = true;
				intent = new Intent(getActivity(), SigninActivity.class);
				startActivity(intent);
				getActivity().overridePendingTransition(R.anim.push_buttom_in,
						R.anim.push_buttom_out);
			} else {
				isRefresh = true;
				intent = new Intent(getActivity(), HistoryActivity.class);
				intent.putExtra("flag", "await_ship");
				startActivityForResult(intent, 2);
				getActivity().overridePendingTransition(R.anim.push_right_in,
						R.anim.push_right_out);
			}
			break;
		case R.id.profile_head_receipt:
			if (uid == 0) {
				isRefresh = true;
				intent = new Intent(getActivity(), SigninActivity.class);
				startActivity(intent);
				getActivity().overridePendingTransition(R.anim.push_buttom_in,
						R.anim.push_buttom_out);
			} else {
				isRefresh = true;
				intent = new Intent(getActivity(), HistoryActivity.class);
				intent.putExtra("flag", "shipped");
				startActivityForResult(intent, 2);
				getActivity().overridePendingTransition(R.anim.push_right_in,
						R.anim.push_right_out);
			}
			break;
		case R.id.profile_head_history:
			if (uid == 0) {
				isRefresh = true;
				intent = new Intent(getActivity(), SigninActivity.class);
				startActivity(intent);
				getActivity().overridePendingTransition(R.anim.push_buttom_in,
						R.anim.push_buttom_out);
			} else {
				isRefresh = true;
				intent = new Intent(getActivity(), HistoryActivity.class);
				intent.putExtra("flag", "finished");
				startActivityForResult(intent, 2);
				getActivity().overridePendingTransition(R.anim.push_right_in,
						R.anim.push_right_out);
			}
			break;
		case R.id.profile_head_collect:
			if (uid == 0) {
				isRefresh = true;
				intent = new Intent(getActivity(), SigninActivity.class);
				startActivity(intent);
				getActivity().overridePendingTransition(R.anim.push_buttom_in,
						R.anim.push_buttom_out);
			} else {
				isRefresh = false;
				intent = new Intent(getActivity(), CollectionActivity.class);
				startActivityForResult(intent, 2);
				getActivity().overridePendingTransition(R.anim.push_right_in,
						R.anim.push_right_out);
			}
			break;
		case R.id.profile_head_address_manage:
			if (uid == 0) {
				isRefresh = true;
				intent = new Intent(getActivity(), SigninActivity.class);
				startActivity(intent);
				getActivity().overridePendingTransition(R.anim.push_buttom_in,
						R.anim.push_buttom_out);
			} else {
				isRefresh = false;
				intent = new Intent(getActivity(), AddressListActivity.class);
				startActivity(intent);
				getActivity().overridePendingTransition(R.anim.push_right_in,
						R.anim.push_right_out);
			}
			break;
		case R.id.profile_head_name:
			if (uid == 0) {
				isRefresh = true;
				intent = new Intent(getActivity(), SigninActivity.class);
				startActivity(intent);
				getActivity().overridePendingTransition(R.anim.push_buttom_in,
						R.anim.push_buttom_out);
			} else {
				isRefresh = true;
				Intent intent2 = new Intent(getActivity(),
						ProfileActivity.class);
				startActivity(intent2);
				getActivity().overridePendingTransition(R.anim.push_buttom_in,
						R.anim.push_buttom_out);
			}
			break;
		case R.id.profile_help:
			intent = new Intent(getActivity(), InfoActivity.class);
			startActivity(intent);
			getActivity().overridePendingTransition(R.anim.push_right_in,
					R.anim.push_right_out);
			break;
		case R.id.profile_head_photo:
			if (uid == 0) {
				isRefresh = true;
				intent = new Intent(getActivity(), SigninActivity.class);
				startActivity(intent);
				getActivity().overridePendingTransition(R.anim.push_buttom_in,
						R.anim.push_buttom_out);
			}else{
				isRefresh = true;
			}
			break;
		case R.id.profile_user:
			if (uid == 0) {
				isRefresh = true;
				intent = new Intent(getActivity(), SigninActivity.class);
				startActivity(intent);
				getActivity().overridePendingTransition(R.anim.push_buttom_in,
						R.anim.push_buttom_out);
			} else {
				isRefresh = true;
				intent = new Intent(getActivity(), ProfileActivity.class);
				startActivity(intent);
				getActivity().overridePendingTransition(R.anim.push_buttom_in,
						R.anim.push_buttom_out);
			}
			break;
		case R.id.profile_head_collect4:
			if (uid == 0) {
				isRefresh = true;
				intent = new Intent(getActivity(), SigninActivity.class);
				startActivity(intent);
				getActivity().overridePendingTransition(R.anim.push_buttom_in,
						R.anim.push_buttom_out);
			} else {
				isRefresh = false;
				Intent intent1 = new Intent(Intent.ACTION_CALL,
						Uri.parse("tel:" + "0754-87125263"));
				startActivity(intent1);
			}
			break;
		case R.id.yijian:
			if (uid == 0) {
				isRefresh = true;
				intent = new Intent(getActivity(), SigninActivity.class);
				startActivity(intent);
				getActivity().overridePendingTransition(R.anim.push_buttom_in,
						R.anim.push_buttom_out);
			} else {
				isRefresh = false;
				agent.startFeedbackActivity();
			}
			break;
		}
	}

	@Override
	public void onRefresh(int id) {
		userInfoModel.getUserInfo();
	}

	@Override
	public void onLoadMore(int id) {

	}

	@Override
	public void onActivityResult(int requestCode, int resultCode, Intent data) {

		if (resultCode == Activity.RESULT_OK
				&& requestCode == Activity.RESULT_OK) {
			Boolean boolean1 = data.getBooleanExtra("login", false);
			if (boolean1 == true) {
				userInfoModel.getUserInfo();
				SESSION session = SESSION.getInstance();
				userInfoModel.getTopicUserInfo(session.uid);
			}
		}
		super.onActivityResult(requestCode, resultCode, data);
	}

	public void OnMessageResponse(String url, JSONObject jo, AjaxStatus status) {
		if (url.endsWith(ProtocolConst.USERINFO)) {
			if (userInfoModel.responseStatus.succeed == 1) {
				user = userInfoModel.user; // 从网络获取
				setUserInfo();
				xlistView.stopRefresh();
				xlistView.setRefreshTime();
				uid = user.Id;
				if (uid == 0) {
					Resources resource = mContext.getResources();
					String click = resource.getString(R.string.click_to_login);
					name.setText(click);
					camera.setVisibility(View.GONE);
					photo.setImageResource(R.drawable.profile_no_avarta_icon);
					profile_user.setVisibility(View.GONE);
				} else {
					setUserInfo();
					profile_user.setVisibility(View.VISIBLE);
				}
			}
		}
	}

	public static USER userInfo(String uid) {
		return new Select().from(USER.class).where("Id = ?", uid)
				.executeSingle();
	}

	@Override
	public void onDestroy() {
		userInfoModel.removeResponseListener(this);
		super.onDestroy();
	}

	@Override
	public void onPause() {
		super.onPause();
		MobclickAgent.onPageEnd("Profile");
	}
}
